package com.zhoug.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.ResourceUtils;
import com.zhoug.common.utils.StringUtils;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义TopView
 *widgets_topViewStyle
 * @Author 35574
 * @Date 2020/7/3
 * @Description
 */
public class TopView extends RelativeLayout {
    private static final String TAG = ">>>TopView";
    private static final int DEFAULT_VIEW_ID = -1;
    private int mLeftLastViewId = DEFAULT_VIEW_ID; // 左侧最右 view 的 id
    private int mRightLastViewId = DEFAULT_VIEW_ID; // 右侧最左 view 的 id
    private List<View> mLeftViewList;//左边的view集合
    private List<View> mRightViewList;//右边的View的集合
    private LinearLayout mTitleContainerView; // 包裹 title 和 subTitle 的容器
    private TextView mTitleView; // 显示 title 文字的 TextView
    private TextView mSubTitleView; // 显示 subTitle 文字的 TextView

    private int mTitleGravity;
    private int topViewHeight;
    private int imageWidth;//默认的图片宽
    private int imageHeight;//默认的图片高
    private int imageTintColor;//图片tint
    private float textSize;//文字大小(除了标题)
    private int textColor;//文字颜色(除了标题)
    private int viewMargin = 0;//子View之间的距离
    private Drawable backImage;//返回图标
    private int titleSize;//标题大小
    private int titleColor;//标题颜色
    private int subTitleSize;//副标题大小
    private int subTitleColor;//副标题颜色

    public TopView(Context context) {
        this(context, null);
    }

    public TopView(Context context, AttributeSet attrs) {
        this(context, attrs, R.style.widgets_TopViewStyle);
    }

    public TopView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TopView, R.attr.widgets_topViewStyle, defStyleAttr);
        topViewHeight = typedArray.getDimensionPixelOffset(R.styleable.TopView_topView_height, 100);
        imageWidth = typedArray.getDimensionPixelOffset(R.styleable.TopView_topView_image_width, 100);
        imageHeight = typedArray.getDimensionPixelOffset(R.styleable.TopView_topView_image_height, 100);
        imageTintColor = typedArray.getColor(R.styleable.TopView_topView_image_tint, -1);
        textSize = typedArray.getDimension(R.styleable.TopView_topView_text_size, ResourceUtils.spTopx(14));
        textColor = typedArray.getColor(R.styleable.TopView_topView_text_color, Color.WHITE);
        viewMargin = typedArray.getDimensionPixelOffset(R.styleable.TopView_topView_viewMargin, ResourceUtils.dpTopx(10));
        titleSize = typedArray.getDimensionPixelSize(R.styleable.TopView_topView_titleSize, ResourceUtils.spTopx(18));
        titleColor = typedArray.getColor(R.styleable.TopView_topView_titleColor, Color.WHITE);
        subTitleSize = typedArray.getDimensionPixelSize(R.styleable.TopView_topView_subTitleSize, ResourceUtils.spTopx(16));
        subTitleColor = typedArray.getColor(R.styleable.TopView_topView_subTitleColor, Color.WHITE);
        mTitleGravity = typedArray.getInt(R.styleable.TopView_topView_title_gravity, Gravity.CENTER_HORIZONTAL);
        String title=typedArray.getString(R.styleable.TopView_topView_title);
        int paddingHorizontal = typedArray.getDimensionPixelOffset(R.styleable.TopView_topView_padding_horizontal, ResourceUtils.dpTopx(15));
        setPadding(paddingHorizontal, getPaddingTop(), paddingHorizontal, getPaddingBottom());


        if (getBackground() == null) {
//            LogUtils.d(TAG, "init:getBackground==null");
            Drawable background = typedArray.getDrawable(R.styleable.TopView_android_background);
            if (background != null) {
                setBackground(background);
            }
        }
        backImage = typedArray.getDrawable(R.styleable.TopView_topView_back_image);
        typedArray.recycle();


//        LogUtils.d(TAG, "init:imageWidth=" + imageWidth);
//        LogUtils.d(TAG, "init:imageHeight=" + imageHeight);
        mLeftViewList = new ArrayList<>();
        mRightViewList = new ArrayList<>();

        setGravity(Gravity.CENTER_VERTICAL);


        if(!StringUtils.isEmpty(title)){
            setTitle(title);
        }
    }

    /**
     * 在TopBar的左侧添加View，如果此前已经有View通过该方法添加到TopBar，则新添加进去的View会出现在已有View的右侧
     *
     * @param view   要添加到 TopBar 左边的 View
     * @param viewId 该按钮的id，可在ids.xml中找到合适的或新增。手工指定viewId是为了适应自动化测试。
     */
    public void addLeftView(View view, int viewId) {
        ViewGroup.LayoutParams viewLayoutParams = view.getLayoutParams();
        LayoutParams layoutParams;
        if (viewLayoutParams != null && viewLayoutParams instanceof LayoutParams) {
            layoutParams = (LayoutParams) viewLayoutParams;
        } else {
            layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        }
        addLeftView(view, viewId, layoutParams);

    }

    /**
     * 在TopBar的左侧添加View，如果此前已经有View通过该方法添加到TopBar，则新添加进去的View会出现在已有View的右侧。
     *
     * @param view         要添加到 TopBar 左边的 View。
     * @param viewId       该按钮的 id，可在 ids.xml 中找到合适的或新增。手工指定 viewId 是为了适应自动化测试。
     * @param layoutParams 传入一个 LayoutParams，当把 Button addView 到 TopBar 时，使用这个 LayouyParams。
     */
    public void addLeftView(View view, int viewId, LayoutParams layoutParams) {
        if (mLeftLastViewId == DEFAULT_VIEW_ID) {
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        } else {
            layoutParams.addRule(RelativeLayout.RIGHT_OF, mLeftLastViewId);
        }
        layoutParams.rightMargin = viewMargin;
        layoutParams.alignWithParent = true; // alignParentIfMissing
        mLeftLastViewId = viewId;
        view.setId(viewId);
        mLeftViewList.add(view);
        addView(view, layoutParams);
    }


    /**
     * 在 TopBar 的右侧添加 View，如果此前已经有 iew 通过该方法添加到 TopBar，则新添加进去的View会出现在已有View的左侧
     *
     * @param view   要添加到 TopBar 右边的View
     * @param viewId 该按钮的id，可在 ids.xml 中找到合适的或新增。手工指定 viewId 是为了适应自动化测试。
     */
    public void addRightView(View view, int viewId) {
        ViewGroup.LayoutParams viewLayoutParams = view.getLayoutParams();
        LayoutParams layoutParams;
        if (viewLayoutParams != null && viewLayoutParams instanceof LayoutParams) {
            layoutParams = (LayoutParams) viewLayoutParams;
        } else {
            layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        }

        this.addRightView(view, viewId, layoutParams);
    }

    /**
     * 在 TopBar 的右侧添加 View，如果此前已经有 View 通过该方法添加到 TopBar，则新添加进去的 View 会出现在已有View的左侧。
     *
     * @param view         要添加到 TopBar 右边的 View。
     * @param viewId       该按钮的 id，可在 ids.xml 中找到合适的或新增。手工指定 viewId 是为了适应自动化测试。
     * @param layoutParams 生成一个 LayoutParams，当把 Button addView 到 TopBar 时，使用这个 LayouyParams。
     */
    public void addRightView(View view, int viewId, LayoutParams layoutParams) {
        if (mRightLastViewId == DEFAULT_VIEW_ID) {
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        } else {
            layoutParams.addRule(RelativeLayout.LEFT_OF, mRightLastViewId);
        }
        layoutParams.leftMargin = viewMargin;
        layoutParams.alignWithParent = true; // alignParentIfMissing
        mRightLastViewId = viewId;
        view.setId(viewId);
        mRightViewList.add(view);
        addView(view, layoutParams);
    }

    public ImageButton addLeftImageButton(int drawableResId, int viewId) {
        return addLeftImageButton(drawableResId, true, viewId);
    }

    /**
     * 根据 resourceId 生成一个 TopBar 的按钮，并 add 到 TopBar 的左边
     *
     * @param drawableResId   按钮图片的 resourceId
     * @param viewId          该按钮的 id，可在ids.xml中找到合适的或新增。手工指定 viewId 是为了适应自动化测试。
     * @param followTintColor 换肤时使用 tintColor 更改它的颜色
     * @return 返回生成的按钮
     */
    public ImageButton addLeftImageButton(int drawableResId, boolean followTintColor, int viewId) {
        ImageButton imageButton = new ImageButton(getContext());
        imageButton.setImageResource(drawableResId);
        imageButton.setBackgroundColor(Color.TRANSPARENT);
        LayoutParams layoutParams = new LayoutParams(imageWidth, imageHeight);
        addLeftView(imageButton, viewId, layoutParams);
        return imageButton;
    }

    public TextView addLeftTextView(String text, int viewId) {
        TextView textView = new TextView(getContext());
        textView.setText(text);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,textSize);
        textView.setTextColor(textColor);
        LayoutParams layoutParams=new LayoutParams(LayoutParams.WRAP_CONTENT, topViewHeight>0 ?topViewHeight :LayoutParams.WRAP_CONTENT);
        addLeftView(textView, viewId,layoutParams);
        return textView;
    }

    public ImageButton addRightImageButton(int drawableResId, int viewId) {
        return addRightImageButton(drawableResId, true, viewId);
    }

    public ImageButton addBackImage(int drawableResId) {
        return addLeftImageButton(drawableResId, R.id.widgets_back_image);
    }

    public ImageButton addBackImage() {
        ImageButton imageButton = new ImageButton(getContext());
        if (backImage != null) {
            imageButton.setImageDrawable(backImage);
        } else {
            imageButton.setImageResource(R.drawable.widgets_back_image);
        }
        imageButton.setBackgroundColor(Color.TRANSPARENT);
        LayoutParams layoutParams = new LayoutParams(imageWidth, imageHeight);
        addLeftView(imageButton, R.id.widgets_back_image, layoutParams);
        return imageButton;
    }


    /**
     * 根据 resourceId 生成一个 TopBar 的按钮，并 add 到 TopBar 的右边
     *
     * @param drawableResId   按钮图片的 resourceId
     * @param viewId          该按钮的 id，可在ids.xml中找到合适的或新增。手工指定 viewId 是为了适应自动化测试。
     * @param followTintColor 换肤时使用 tintColor 更改它的颜色
     * @return 返回生成的按钮
     */
    public ImageButton addRightImageButton(int drawableResId, boolean followTintColor, int viewId) {
        ImageButton imageButton = new ImageButton(getContext());
        imageButton.setImageResource(drawableResId);
        imageButton.setBackgroundColor(Color.TRANSPARENT);
        LayoutParams layoutParams = new LayoutParams(imageWidth, imageHeight);
        addRightView(imageButton, viewId, layoutParams);
        return imageButton;
    }

    public TextView addRightTextView(String text, int viewId) {
        TextView textView = new TextView(getContext());
        textView.setText(text);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,textSize);
        textView.setTextColor(textColor);
        LayoutParams layoutParams=new LayoutParams(LayoutParams.WRAP_CONTENT, topViewHeight>0 ?topViewHeight :LayoutParams.WRAP_CONTENT);
        addRightView(textView, viewId,layoutParams);
        return textView;
    }


    public TextView setTitle(String title) {
        TextView titleView = getTitleView();
        if (title != null) {
            titleView.setText(title);
            titleView.setVisibility(VISIBLE);
        } else {
            titleView.setVisibility(GONE);
        }
        return titleView;
    }

    public TextView setSubTitle(String title) {
        TextView titleView = getSubTitleView();
        if (title != null) {
            titleView.setText(title);
            titleView.setVisibility(VISIBLE);
        } else {
            titleView.setVisibility(GONE);
        }
        return titleView;
    }


    private TextView getTitleView() {
        if (mTitleView == null) {
            mTitleView = new TextView(getContext());
            mTitleView.setGravity(Gravity.CENTER);
            mTitleView.setSingleLine(true);
            mTitleView.setEllipsize(TextUtils.TruncateAt.END);
            mTitleView.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleSize);
            mTitleView.setTextColor(titleColor);
            getTitleContainerView().addView(mTitleView, 0);
        }
        return mTitleView;
    }

    private TextView getSubTitleView() {
        if (mSubTitleView == null) {
            mSubTitleView = new TextView(getContext());
            mSubTitleView.setGravity(Gravity.CENTER);
            mSubTitleView.setSingleLine(true);
            mSubTitleView.setEllipsize(TextUtils.TruncateAt.END);
            mSubTitleView.setTextSize(TypedValue.COMPLEX_UNIT_PX, subTitleSize);
            mSubTitleView.setTextColor(subTitleColor);
            getTitleContainerView().addView(mSubTitleView);
        }
        return mSubTitleView;
    }

    private LinearLayout getTitleContainerView() {
        if (mTitleContainerView == null) {
            mTitleContainerView = new LinearLayout(getContext());
            mTitleContainerView.setOrientation(LinearLayout.VERTICAL);
            mTitleContainerView.setGravity(Gravity.CENTER);
            LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            addView(mTitleContainerView, layoutParams);
        }

        return mTitleContainerView;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) {
            setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), topViewHeight);
        }
        if (mTitleContainerView != null) {
            // 计算左侧 View 的总宽度
            int leftViewWidth = getPaddingLeft();
            for (int leftViewIndex = 0; leftViewIndex < mLeftViewList.size(); leftViewIndex++) {
                View view = mLeftViewList.get(leftViewIndex);
                if (view.getVisibility() != GONE) {
                    leftViewWidth += view.getMeasuredWidth();
                    ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                    if (layoutParams instanceof LayoutParams) {
                        LayoutParams layoutParams1 = (LayoutParams) layoutParams;
                        leftViewWidth += layoutParams1.leftMargin + layoutParams1.rightMargin;
                    }

                }
            }
            // 计算右侧 View 的总宽度
            int rightViewWidth = getPaddingRight();
            for (int rightViewIndex = 0; rightViewIndex < mRightViewList.size(); rightViewIndex++) {
                View view = mRightViewList.get(rightViewIndex);
                if (view.getVisibility() != GONE) {
                    rightViewWidth += view.getMeasuredWidth();
                    ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                    if (layoutParams instanceof LayoutParams) {
                        LayoutParams layoutParams1 = (LayoutParams) layoutParams;
                        rightViewWidth += layoutParams1.leftMargin + layoutParams1.rightMargin;
                    }
                }
            }
//            LogUtils.d(TAG, "onMeasure:leftViewWidth=" + leftViewWidth);
//            LogUtils.d(TAG, "onMeasure:rightViewWidth=" + rightViewWidth);
            // 计算 titleContainer 的最大宽度
            int titleContainerWidth;
            if ((mTitleGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.CENTER_HORIZONTAL) {
//                LogUtils.d(TAG, "onMeasure:标题水平居中");
                // 标题水平居中，左右两侧的占位要保持一致
                titleContainerWidth = MeasureSpec.getSize(widthMeasureSpec) -
                        Math.max(leftViewWidth, rightViewWidth) * 2;
            } else {
//                LogUtils.d(TAG, "onMeasure:标题左对齐");
                // 标题非水平居中，左右两侧的占位按实际计算即可
                titleContainerWidth = MeasureSpec.getSize(widthMeasureSpec) - leftViewWidth - rightViewWidth;
            }
            if (titleContainerWidth < 0) {
                titleContainerWidth = 0;
            }
//            LogUtils.d(TAG, "onMeasure:titleContainerWidth=" + titleContainerWidth);
            int titleContainerWidthMeasureSpec = MeasureSpec.makeMeasureSpec(titleContainerWidth, MeasureSpec.EXACTLY);
            mTitleContainerView.measure(titleContainerWidthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (mTitleContainerView != null) {
            int titleContainerViewWidth = mTitleContainerView.getMeasuredWidth();
            int titleContainerViewHeight = mTitleContainerView.getMeasuredHeight();
            int titleContainerViewTop = (b - t - mTitleContainerView.getMeasuredHeight()) / 2;
            int titleContainerViewLeft = getPaddingLeft();
            if ((mTitleGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.CENTER_HORIZONTAL) {
                // 标题水平居中
                titleContainerViewLeft = (r - l - mTitleContainerView.getMeasuredWidth()) / 2;
            } else {
                // 标题非水平居中
                // 计算左侧 View 的总宽度
                for (int leftViewIndex = 0; leftViewIndex < mLeftViewList.size(); leftViewIndex++) {
                    View view = mLeftViewList.get(leftViewIndex);
                    if (view.getVisibility() != GONE) {
                        titleContainerViewLeft += view.getMeasuredWidth();
                        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                        if (layoutParams instanceof LayoutParams) {
                            LayoutParams layoutParams1 = (LayoutParams) layoutParams;
                            titleContainerViewLeft += layoutParams1.leftMargin + layoutParams1.rightMargin;
                        }
                    }
                }
            }
            mTitleContainerView.layout(titleContainerViewLeft, titleContainerViewTop,
                    titleContainerViewLeft + titleContainerViewWidth,
                    titleContainerViewTop + titleContainerViewHeight);
        }
    }


}
